import { _decorator, Component, Label } from 'cc';
import { Game } from '../core/Game';
import { Databus } from '../core/Databus';
import { BilliardGame } from './BilliardGame';
import { EventManager } from '../core/EventManager';
import { UniformFunction } from '../platform/UniformFunction';
const { ccclass, property } = _decorator;

const databus = Databus.Instance();
@ccclass('FancyBattleLogic')
export class FancyBattleLogic extends Component {
  private timestamp = 0;
  private brokenHitCount = 0;
  onLoad() {
    EventManager.Instance().AddEventListener('StartGame', this, this.startGame);
    EventManager.Instance().AddEventListener('ChangeUserHitBall', this, this.changeUserHitBall);
  }
  public start() {
    if (Game.Instance().battleCate.isFancyBattle()) {
      this.node.active = true;
    } else {
      this.node.active = false;
    }
  }
  public update(deltaTime: number) {
    this.timestamp += 1;
    if (this.timestamp > 60) {
      this.node.getChildByName('OneShotClear').active = false;
    }
    this.updateFancyLevel();
  }
  public startGame() {
    if (!Game.Instance().battleCate.isFancyBattle()) {
      return;
    }
    const conf = databus.hurdles.getHurdlesConfig();
    if (conf.maxHitNum === 1) {
      this.node.getChildByName('OneShotClear').active = true;
      this.timestamp = 0;
    } else {
      this.node.getChildByName('OneShotClear').active = false;
    }
    this.brokenHitCount = 0;

    if (databus.hurdles.isFinishedAllBarrier()) {
      new UniformFunction().showInfoToast('恭喜你，已完成所有关卡', 3000);
    }
  }
  public changeUserHitBall() {
    if (!Game.Instance().battleCate.isFancyBattle()) {
      return;
    }
    this.brokenHitCount += 1;
    const conf = databus.hurdles.getHurdlesConfig();
    if (this.brokenHitCount > conf.brokenNum) {
      EventManager.Instance().Emit('FastEndFancyGame', { win: 0 });
    }
  }
  public updateFancyLevel() {
    const conf = databus.hurdles.getHurdlesConfig();

    const lv = databus.hurdles.levelIndex;
    this.node.getChildByName('BarrierLevelText').getChildByName('Label').getComponent(Label).string = `第${lv}关`;

    var ln = databus.hurdles.maxHitNum() - BilliardGame.Instance().currentHitGanCount();
    if (ln <= 0) ln = 0; // 在切换过程中可能出现异常数据
    this.node.getChildByName('LeftGanText').getChildByName('LeftCount').getComponent(Label).string = `${ln}`;

    this.node.getChildByName('BrokenGanText').getChildByName('LeftCount').getComponent(Label).string = `${conf.brokenNum}`;

    this.node.getChildByName('Coin').getChildByName('Label').getComponent(Label).string = `+ ${conf.coin}`;
  }
}

